<template>
  <ul
    ref="sortableList"
    class="sortable-list $sortableListClass$"
    id="sortableListId"
    name="sortableListName"
  >
    <li v-for="(item, index) in list" :key="item.id" :data-id="item.id">
      {{ item.name }}
    </li>
  </ul>
</template>

<script>
import Sortable from 'sortablejs'

export default {
  name: 'DraggableList',
  props: {
    list: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      colors: ['#6562C9', '#A96BD8', '#3E5FC0', '#5A82FC', '#219BE6', '#EFF3FE'],
      sortable: null
    }
  },
  mounted() {
    this.initSortable()
  },
  beforeDestroy() {
    if (this.sortable) {
      this.sortable.destroy()
    }
  },
  methods: {
    initSortable() {
      this.sortable = Sortable.create(this.$refs.sortableList, {
        animation: 150, // 动画效果持续时间
        onEnd: this.onSortEnd
      })
    },
    onSortEnd(e) {
      // 触发自定义事件，通知父组件列表已排序
      console.log(e)
      this.$emit('sort-end', e)
      const { newIndex, oldIndex } = e
      // 如果你想在前端直接更新列表顺序，可以这样做：
      const movedItem = this.list.splice(oldIndex, 1)[0]
      this.list.splice(newIndex, 0, movedItem)
    }
  }
}
</script>

<style scoped>
.sortable-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.sortable-list li {
  margin: 5px 0;
  padding: 10px;
  border: 1px solid #ccc;
  cursor: move;
}
</style>
